<template>
    <div class="add-shijuan-container">
      <el-form 
        ref="ruleFormRef" 
        :model="ruleForm" 
        :rules="rules" 
        label-width="100px"
        class="compact-form"
      >
        <!-- 基本信息 -->
        <el-form-item label="年级" prop="level">
          <el-select 
            v-model="ruleForm.level" 
            placeholder="请选择年级" 
            @change="handleGradeChange"
            :loading="loading"
            style="width: 300px"
          >
            <el-option 
              :label="item.name" 
              :value="item.value" 
              v-for="item in levelStore.list" 
              :key="item.value" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="学科" prop="subject">
          <el-select 
            v-model="ruleForm.subject" 
            placeholder="请先选择年级"
            :disabled="!ruleForm.level"
            :loading="loading"
            style="width: 300px"
          >
            <el-option 
              :label="subject.name" 
              :value="subject.id" 
              v-for="subject in filteredSubjects" 
              :key="subject.id" 
            />
          </el-select>
          <!-- 添加当前学科名称显示 -->
          <el-tag v-if="ruleForm.subject !== null" style="margin-left: 10px;">
            {{ getSubjectName(ruleForm.subject) }}
          </el-tag>
        </el-form-item>
        
        <el-form-item label="试卷类型" prop="paperType">
          <el-select 
            v-model="ruleForm.paperType" 
            @change="handlePaperTypeChange"
            style="width: 300px"
          >
            <el-option 
              :label="item.name" 
              :value="item.value" 
              v-for="item in shijuanStore.shijuanclass" 
              :key="item.value" 
            />
          </el-select>
        </el-form-item>
        
        <!-- 日期范围选择器 -->
        <el-form-item 
          v-if="showDatePicker"
          label="日期范围" 
          prop="dateRange"
        >
          <el-date-picker
            v-model="ruleForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 400px"
          />
        </el-form-item>
        
        <el-form-item label="试卷名称" prop="name">
          <el-input 
            v-model="ruleForm.name" 
            placeholder="请输入试卷名称"
            style="width: 400px"
          />
        </el-form-item>
        
        <!-- 动态标题区域 -->
        <div v-for="(title, index) in ruleForm.titles" :key="index" class="dynamic-title-item compact">
          <el-form-item 
            :label="`标题 ${index + 1}`" 
            class="title-item"
          >
            <div class="title-content">
              <el-input 
                v-model="title.value" 
                placeholder="请输入标题内容"
                style="width: 300px;"
                size="small"
              />
              <div class="title-actions">
                <el-button type="danger" size="small" @click="removeTitle(index)" plain>
                  删除
                </el-button>
                <el-button type="primary" size="small" @click="addQuestions(index)" plain>
                  添加题目
                </el-button>
              </div>
            </div>
            
            <!-- 题目列表 -->
            <div class="questions-list compact" v-if="title.questions && title.questions.length > 0">
              <div 
                v-for="(q, qIndex) in title.questions" 
                :key="qIndex" 
                class="question-item compact"
              >
                <div class="question-content-wrapper">
                  <span class="question-index">{{ qIndex + 1 }}.</span>
                  <span class="question-text">{{ q.content }}</span>
                  <div class="question-actions">
                    <el-button 
                      type="danger" 
                      size="small" 
                      @click="removeQuestion(index, qIndex)"
                      plain
                    >删除</el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </div>
        
        <el-form-item label="建议时长" prop="duration">
          <el-input 
            v-model="ruleForm.duration" 
            placeholder="请输入建议时长（分钟）" 
            type="number" 
            min="0" 
            style="width: 200px"
          >
            <template #append>分钟</template>
          </el-input>
        </el-form-item>
        
        <el-form-item class="form-actions">
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            更新试卷
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="success" @click="addTitle">
            添加标题
          </el-button>
        </el-form-item>
      </el-form>
      
      <!-- 添加题目对话框 -->
      <Addzujiantimu ref="addQuestionDialogRef" @addQuestions="handleAddQuestions" />
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, computed, onMounted, reactive, watch } from 'vue'
  import { type FormInstance, type FormRules, ElMessage } from 'element-plus'
  import { useLevelStore } from '@/stores/level'
  import { useRouter, useRoute } from 'vue-router'
  import { getSubjectDetail, type Subject } from '@/api/juanti'
  import { useshijuanStore } from '@/stores/juanti'
  import Addzujiantimu from './Addzujiantimu.vue'
  import type { QuestionItem } from '@/api/juanti'
  import { getExamPaperDetail, editExamPaper, type ExamPaperDetail } from '@/api/juanti'
  
  // 创建路由实例
  const router = useRouter()
  const route = useRoute()
  const levelStore = useLevelStore()
  const shijuanStore = useshijuanStore()
  const addQuestionDialogRef = ref<InstanceType<typeof Addzujiantimu>>()
  
  // 变量声明
  const loading = ref(false)
  // 学科数据缓存 {年级ID: 学科对象}
  const subjectCache = ref<Record<number, Subject>>({})
  const filteredSubjects = ref<Subject[]>([])
  const ruleFormRef = ref<FormInstance>()
  const currentTitleIndex = ref(-1)
  
  // 试卷ID
  const paperId = ref(Number(route.params.id))
  
  // 表单数据 - 修复subject类型为number|null
  const ruleForm = reactive({
    name: '',
    level: null as number | null,
    subject: null as number | null, // 明确指定为数字类型
    paperType: 1,
    duration: '',
    dateRange: null as [string, string] | null,
    id: null as number | null,
    levelName: "",
    titles: [] as Array<{
      value: string
      questions: Array<{
        id: number
        questionType: number
        content: string
        difficulty: number
      }>
    }>
  })
  
  // 计算属性，控制日期选择器是否显示
  const showDatePicker = computed(() => {
    return ruleForm.paperType === 2
  })
  
  // 年级变化处理
  const handleGradeChange = async (val: number) => {
    const level = levelStore.list.find(item => item.value == val)
    ruleForm.levelName = level?.name || ""
    
    // 重置学科选择
    ruleForm.subject = null
    
    // 如果该年级学科已缓存，直接使用
    if (subjectCache.value[val]) {
      filteredSubjects.value = [subjectCache.value[val]]
      return
    }
    
    // 否则调用接口获取学科详情
    try {
      loading.value = true
      const response = await getSubjectDetail(val)
      
      if (response?.code === 1 && response.response) {
        const subjectData = response.response
        
        // 创建学科对象
        const subject: Subject = {
          id: subjectData.id,
          name: subjectData.name,
          level: subjectData.level,
          levelName: subjectData.levelName
        }
        
        // 缓存并设置学科
        subjectCache.value[val] = subject
        filteredSubjects.value = [subject]
      } else {
        console.error('获取学科详情失败:', response)
        filteredSubjects.value = []
        ElMessage.error('获取学科详情失败')
      }
    } catch (error) {
      console.error('加载学科详情失败:', error)
      filteredSubjects.value = []
      ElMessage.error('加载学科详情失败')
    } finally {
      loading.value = false
    }
  }
  
  // 试卷类型变化处理
  const handlePaperTypeChange = (value: number) => {
    if (value !== 2) {
      ruleForm.dateRange = null
    }
  }
  
  // 监听年级变化
  watch(() => ruleForm.level, () => {
    ruleForm.subject = null
  })
  
  // 添加标题
  const addTitle = () => {
    ruleForm.titles.push({ 
      value: '',
      questions: [] 
    })
  }
  
  // 删除标题
  const removeTitle = (index: number) => {
    ruleForm.titles.splice(index, 1)
  }
  
  // 打开添加题目对话框
  const addQuestions = (index: number) => {
    currentTitleIndex.value = index
    if (addQuestionDialogRef.value) {
      addQuestionDialogRef.value.openDialog()
    }
  }
  
  // 处理添加的题目
  const handleAddQuestions = (questions: QuestionItem[]) => {
    if (currentTitleIndex.value === -1) return
    
    // 添加到当前标题
    const currentTitle = ruleForm.titles[currentTitleIndex.value]
    
    // 避免重复添加
    const newQuestions = questions.filter(q => 
    !currentTitle.questions.some(existing => existing.id === q.id))
    
    if (newQuestions.length === 0) {
      ElMessage.warning('所选题目已存在')
      return
    }
    
    // 将题目添加到当前标题 - 使用title字段
    currentTitle.questions.push(...newQuestions.map(q => ({
      id: q.id,
      questionType: q.questionType,
      content: q.title,
      difficulty: q.difficult
    })))
    
    ElMessage.success(`成功添加 ${newQuestions.length} 个题目`)
  }
  
  // 移除题目
  const removeQuestion = (titleIndex: number, questionIndex: number) => {
    ruleForm.titles[titleIndex].questions.splice(questionIndex, 1)
    ElMessage.success('题目已移除')
  }
  
  // 表单验证规则
  const rules = ref<FormRules>({
    name: [
      { required: true, message: '请输入试卷名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度应在2到50个字符之间', trigger: 'blur' },
    ],
    level: [
      {
        required: true,
        message: '请选择年级',
        trigger: 'change',
      },
    ],
    subject: [
      {
        required: true,
        message: '请选择学科',
        trigger: 'change',
      },
    ],
    paperType: [
      {
        required: true,
        message: '请选择试卷类型',
        trigger: 'change',
      }
    ],
    duration: [
      { required: true, message: '请输入建议时长', trigger: 'blur' },
      { pattern: /^[1-9]\d*$/, message: '请输入大于0的整数', trigger: 'blur' }
    ],
    dateRange: [
      {
        type: 'array',
        required: ruleForm.paperType === 2,
        message: '请选择日期范围',
        trigger: 'change',
      }
    ]
  })
  
  // 根据学科ID获取学科名称
  const getSubjectName = (subjectId: number): string => {
    const subject = filteredSubjects.value.find(s => s.id === subjectId)
    return subject ? subject.name : '未知学科'
  }
  
  // 加载试卷详情 - 修复subject类型转换
  const loadPaperDetail = async (id: number) => {
    try {
      loading.value = true
      const response = await getExamPaperDetail(id)
      
      if (response?.code === 1 && response.response) {
        const paper = response.response
        
        // 填充表单数据
        ruleForm.id = paper.id
        ruleForm.name = paper.name
        ruleForm.level = paper.level
        // 确保subjectId转换为数字类型
        ruleForm.subject = Number(paper.subjectId)
        ruleForm.paperType = paper.paperType
        ruleForm.duration = paper.suggestTime.toString()
        
        // 日期范围处理 - 修复类型错误
        if (paper.paperType === 2 && paper.limitDateTime) {
          // 明确类型为字符串数组
          const dateRange = paper.limitDateTime as unknown as string[];
          
          // 确保日期格式正确
          ruleForm.dateRange = [
            dateRange[0]?.split('T')[0] || '',
            dateRange[1]?.split('T')[0] || ''
          ]
        } else {
          ruleForm.dateRange = null
        }
        
        // 填充标题和题目
        ruleForm.titles = paper.titleItems.map((titleItem: { name: any; questionItems: any[] }) => ({
          value: titleItem.name,
          questions: titleItem.questionItems.map(q => ({
            id: q.id,
            questionType: q.questionType,
            content: q.title,
            difficulty: q.difficult
          }))
        }))
        
        // 更新年级名称
        const level = levelStore.list.find(item => item.value == paper.level)
        ruleForm.levelName = level?.name || ""
        
        // 预加载当前试卷的学科数据
        if (paper.level) {
          await handleGradeChange(paper.level)
          
          // 确保学科选择器显示正确值
          ruleForm.subject = Number(paper.subjectId)
        }
      } else {
        ElMessage.error('获取试卷详情失败: ' + (response?.message || '未知错误'))
      }
    } catch (error: any) {
      console.error('加载试卷详情失败:', error)
      ElMessage.error('加载试卷详情失败: ' + (error.message || '未知错误'))
    } finally {
      loading.value = false
    }
  }
  
  // 提交表单 (编辑试卷)
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        // 检查是否有标题但没有添加题目
        const hasTitleWithoutQuestions = ruleForm.titles.some(
          title => title.value.trim() !== '' && title.questions.length === 0
        )
        
        if (hasTitleWithoutQuestions) {
          ElMessage.warning('请为每个标题添加至少一个题目')
          return
        }
        
        // 准备提交数据
        const postData = {
          id: ruleForm.id,
          level: ruleForm.level,
          subjectId: ruleForm.subject, // 直接使用数字类型
          paperType: ruleForm.paperType,
          name: ruleForm.name,
          suggestTime: parseInt(ruleForm.duration),
          limitDateTime: ruleForm.paperType === 2 && ruleForm.dateRange 
            ? ruleForm.dateRange 
            : null,
          titleItems: ruleForm.titles.map(title => ({
            name: title.value,
            questionItems: title.questions.map(q => ({
              id: q.id,
              questionType: q.questionType,
              subjectId: Number(ruleForm.subject),
              title: q.content,
              gradeLevel: ruleForm.level,
              difficult: q.difficulty
            }))
          }))
        }
        
        // 调用编辑接口
        updatePaper(postData)
      } else {
        console.log('表单验证失败:', fields)
        ElMessage.error('请检查表单填写是否正确')
      }
    })
  }
  
  // 更新试卷
  const updatePaper = async (data: any) => {
    try {
      loading.value = true
      const response = await editExamPaper(data)
      
      if (response?.code === 1) {
        ElMessage.success('试卷更新成功')
        router.push('/shijuanlist')
      } else {
        const errorMsg = response?.message || '试卷更新失败'
        ElMessage.error(errorMsg)
      }
    } catch (error: any) {
      console.error('更新试卷失败:', error)
      ElMessage.error('更新试卷失败: ' + (error.message || '未知错误'))
    } finally {
      loading.value = false
    }
  }
  
  // 重置表单
  const resetForm = () => {
    if (paperId.value) {
      loadPaperDetail(paperId.value)
    }
  }
  
  // 初始化加载数据
  onMounted(() => {
    if (paperId.value) {
      loadPaperDetail(paperId.value)
    } else {
      ElMessage.error('无效的试卷ID')
      router.push('/shijuanlist')
    }
  })
  </script>
  
  <style scoped>
  .add-shijuan-container {
    padding: 20px;
    max-width: 900px;
  }
  
  .compact-form .el-form-item {
    margin-bottom: 16px;
  }
  
  .dynamic-title-item.compact {
    margin-bottom: 12px;
    padding: 8px 0;
    border-top: 1px solid #eee;
  }
  
  .title-content {
    display: flex;
    gap: 8px;
    margin-bottom: 8px;
    align-items: center;
  }
  
  .title-actions {
    display: flex;
    gap: 6px;
  }
  
  .questions-list.compact {
    margin-top: 6px;
    width: 100%;
  }
  
  .question-item.compact {
    margin-bottom: 8px;
    padding: 8px;
    border-radius: 4px;
    background-color: #f8f9fa;
    border: 1px solid #eee;
  }
  
  .question-content-wrapper {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    width: 100%;
  }
  
  .question-index {
    font-weight: bold;
    min-width: 24px;
  }
  
  .question-text {
    flex: 1;
    white-space: pre-wrap;
    word-break: break-word;
  }
  
  .question-actions {
    margin-left: auto;
  }
  
  .form-actions {
    margin-top: 16px;
    padding-top: 12px;
    border-top: 1px solid #eee;
  }
  
  .el-button--small {
    padding: 5px 10px;
    font-size: 12px;
  }
  </style>